<template>
  <div>
    <!-- 列表 -->
    <el-table :data="pageList" row-key="id" v-loading="initLoading">
      <el-table-column label="页面名称" prop="page_name">
        <template #default="scope">
          <span>{{ scope.row.page_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="100">
        <template #default="scope">
          <template v-if="selectedActive == scope.row.id">
            <el-button
              type="primary"
              size="small"
              @click="selectedItem(scope.row)"
              >选取</el-button
            >
          </template>
          <template v-else>
            <el-button size="small" @click="selectedItem(scope.row)"
              >选取</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="flex end">
      <page :listPage="listPage" @change="pageChange"></page>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: "storeDiyLinkModalPage",
};
</script>
<script setup lang="ts">
import { ref, getCurrentInstance, watch, onMounted } from "vue";
import { getDiyPageList } from "@/api/store/diy_page";
import { diyLinkType, listPageType, Result, ResultError } from "@/types";
import { useConfig } from "@/store";

const configStore = useConfig();

const props = withDefaults(
  defineProps<{
    linkItem?: diyLinkType;
  }>(),
  {
    linkItem: () => {
      return {};
    },
  }
);

const {
  proxy: { $utils },
} = getCurrentInstance() as any;

const initLoading = ref<boolean>(true);

const pageList = ref<any>([]);

const toInit = () => {
  let obj: any = {};
  obj.page = listPage.value.page;
  obj.limit = listPage.value.limit;
  initLoading.value = true;
  getDiyPageList(obj)
    .then((res: Result) => {
      initLoading.value = false;
      pageList.value = res.data.data;
      listPage.value.total = res.data.total;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const pageChange = (res: listPageType) => {
  listPage.value = res;
  toInit();
};

const listPage = ref<listPageType>({
  total: 0,
  limit: configStore.getPageLimit,
  page: 1,
});

const emit = defineEmits(["change"]);

const selectedActive = ref<number | string>(props.linkItem?.value || "");

const selectedData = ref<diyLinkType>(props.linkItem);

const selectedItem = (item: { page_name: string; id: number | string }) => {
  selectedActive.value = item.id;
  selectedData.value = {
    type: "diy",
    title: item.page_name,
    desc: "自定义页面",
    value: item.id,
  };
  emit("change", selectedData.value);
};
onMounted(() => {
  toInit();
});
</script>